package com.example.demo.controller;

import com.example.demo.common.APPUtils;
import com.example.demo.common.ArticleUtils;
import com.example.demo.common.CommonResult;
import com.example.demo.common.SessionUtils;
import com.example.demo.model.ArticleInfo;
import com.example.demo.model.UserInfo;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;


@RestController
@RequestMapping("/art")
public class ArticleController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private UserService userService;

    @RequestMapping("/publish")
    public CommonResult publish(@RequestBody ArticleInfo articleInfo, HttpServletRequest request) {
        // 1. 获取当前用户详信息
        UserInfo userInfo = SessionUtils.getUser(request);
        articleInfo.setUid(userInfo.getId());
        articleInfo.setPhoto(userInfo.getPhoto());
        // 2. 校验参数
         if(!APPUtils.hasLength(articleInfo.getContent(), articleInfo.getSummary(), articleInfo.getTitle())) {
             return CommonResult.fail(-1, "非法参数！");
         }
        // 3. 提交到数据库中
        int rows = articleService.publish(articleInfo);
        // 4. 返回
        return CommonResult.success(rows);
    }

    @RequestMapping("/get_mylist")
    public CommonResult getMylist(HttpServletRequest request) {
        // 1. 获取当前登录用户
        UserInfo userInfo = SessionUtils.getUser(request);
        // 2. 通过此用户发布的所有文章
        List<ArticleInfo> list = articleService.getListByUid(userInfo.getId());
        // 3. 标题 / 正文太长 处理
        ArticleUtils.substringList(list);
        // 4. 返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("user", userInfo);
        map.put("list", list);
        return CommonResult.success(map);
    }

    @RequestMapping("/delete")
    public CommonResult delete(@RequestBody ArticleInfo articleInfo, HttpServletRequest request) {
        // 1. 获取当前登录用户的id
        int uid = SessionUtils.getUser(request).getId();
        // 2. 设置到文章对象里
        articleInfo.setUid(uid);
        // 3. 删除
        int rows = articleService.delete(articleInfo);
        // 3. 返回
        return CommonResult.success(rows);
    }

    @RequestMapping("/get_art")
    public CommonResult getArt(@RequestBody ArticleInfo articleInfo, HttpServletRequest request) {
        // 1. 获取当前登录用户的id
        int uid = SessionUtils.getUser(request).getId();
        // 2. 设置到文章对象里
        articleInfo.setUid(uid);
        // 3. 查询文章
        ArticleInfo art = articleService.getArt(articleInfo);
        // 4. 返回(查询不到一个对象，是null；如果查询不到对象集合，返回的是空集合)
        return art == null ? CommonResult.fail(-1, "查询不到！") : CommonResult.success(art);
    }

    @RequestMapping("/update")
    public CommonResult update(@RequestBody ArticleInfo articleInfo, HttpServletRequest request) {
        // 0. 确认用户
        int uid = SessionUtils.getUser(request).getId();
        articleInfo.setUid(uid);
        // 1. 校验参数
        if(!APPUtils.hasLength(articleInfo.getContent(), articleInfo.getSummary(), articleInfo.getTitle())) {
            return CommonResult.fail(-1, "非法参数！");
        }
        // 2. 修改
        int rows = articleService.update(articleInfo);
        // 3. 返回
        return CommonResult.success(rows);
    }

    @RequestMapping("/detail")
    public CommonResult detail(@RequestBody ArticleInfo articleInfo, HttpServletRequest request) throws ExecutionException, InterruptedException {
        // 1. 查询文章信息
        ArticleInfo art = articleService.getArtByAid(articleInfo);
        // 2. 校验文章是否存在
        if(art == null) {
            return CommonResult.fail(-1, "非法参数!");
        }
        // 3. 根据uid查询用户总文章数的任务
        FutureTask<Integer> task1 = new FutureTask<Integer>(() -> {
            return articleService.getArtNumberByUid(art.getUid());
        });
        // 4. 根据uid查询用户信息的任务
        FutureTask<UserInfo> task2 = new FutureTask<UserInfo>(() -> {
            return userService.getUserByUid(art.getUid());
        });
        // 5. 根据aid更新阅读量的任务
        FutureTask<Integer> task3 = new FutureTask<Integer>(() -> {
            return articleService.incrementRCount(art.getId());
        });
        // 6. 线程池执行任务
        APPUtils.THREAD_POOL.submit(task1);
        APPUtils.THREAD_POOL.submit(task2);
        APPUtils.THREAD_POOL.submit(task3);
        // 7. 构造响应数据,并返回
        Map<String, Object> map = new HashMap<>();
        map.put("login", SessionUtils.getUser(request) != null);
        map.put("count", task1.get());
        map.put("user", task2.get());
        map.put("art", art);
        task3.get();
        return CommonResult.success(map);
    }

    @RequestMapping("/all_list")
    public CommonResult allList(@RequestParam("pindex") Integer pindex, @RequestParam("psize") Integer psize, HttpServletRequest request) throws ExecutionException, InterruptedException {
        // 1. 校验参数
        if(pindex == null || pindex < 1) {
            pindex = 1;//页码
        }
        if(psize == null || psize < 2) {
            psize = 2;//页内博客数
        }
        // 2. 并发进行文章列表和总页数的查询
        Integer index = pindex;
        Integer size = psize;
        FutureTask<List<ArticleInfo>> task1 = new FutureTask<List<ArticleInfo>>(() -> {
            int offset = size * (index - 1);
           return articleService.getSubList(size, offset);
        });
        FutureTask<Integer> task2 = new FutureTask<Integer>(() -> {
            return articleService.getNumber();
        });
        APPUtils.THREAD_POOL.submit(task1);
        APPUtils.THREAD_POOL.submit(task2);
        //因为数据库的一条语句是保证原子性的，所以线程安全
        // 3. 数据进一步处理
        int count = task2.get();
        int pMax = (int)Math.ceil(count * 1.0 / size);
        if(pMax != 0 && index > pMax) {
            return CommonResult.fail(-2, "并不存在第" + index + "页，目前正在返回首页！");
        }
        List<ArticleInfo> list = task1.get();
        ArticleUtils.substringList(list);
        // 4. 构造数据并返回
        Map<String, Object> map = new HashMap<>();
        map.put("login", SessionUtils.getUser(request) != null);
        map.put("list", list);
        map.put("pMax", pMax);
        return CommonResult.success(map);
    }

}
